package com.nit.lab.service.basic.impl;


import com.alibaba.fastjson.JSONObject;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.nit.lab.dto.basic.GoodsDTO;
import com.nit.lab.dto.basic.GoodsListDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.basic.GoodsEntity;
import com.nit.lab.entity.basic.GoodsListEntity;
import com.nit.lab.mapper.basic.GoodsListMapper;
import com.nit.lab.mapper.basic.GoodsMapper;
import com.nit.lab.service.basic.GoodsService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsListMapper goodsListMapper;
    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = goodsMapper.count4Table(
                tableReqDTO.parseQueryParam("goodsName"));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                goodsMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("goodsName")
                        ));
        for(int i=0;i<pagingDTO.getData().size();i++){
            GoodsDTO goodsDTO =  (GoodsDTO) pagingDTO.getData().get(i);
            if(goodsDTO.getCreator2()==null)
            {
                goodsDTO.setCreator2(goodsDTO.getCreator());
            }
            if(goodsDTO.getOwner2()==null){
                goodsDTO.setOwner2(goodsDTO.getOwner());
            }
            pagingDTO.getData().set(i,(Object) goodsDTO);
        }
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(GoodsDTO goodsDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        GoodsEntity goodsEntity = mapperFactory.getMapperFacade().map(goodsDTO, GoodsEntity.class);
        goodsEntity.setStatus(0);
        goodsEntity.setCreateTime(new Date());
        goodsMapper.add(goodsEntity);
        return goodsEntity.getGoodsId().intValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(GoodsDTO goodsDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        GoodsEntity goodsEntity = mapperFactory.getMapperFacade().map(goodsDTO, GoodsEntity.class);
        System.out.println(goodsEntity);
        return goodsMapper.update(goodsEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String ids) throws Exception {
        String[] arrayGoodsId = ids.split(",");
        for (int i = 0; i < arrayGoodsId.length; i++) {
            GoodsEntity goodsEntity = goodsMapper.getById(Integer.parseInt(arrayGoodsId[i]));
            goodsMapper.addHistory(goodsEntity);
            goodsMapper.remove(Long.parseLong(arrayGoodsId[i]));
            if(goodsEntity.getStatus()==0){
                goodsListMapper.dropNum(goodsEntity.getListId());
            }
        }
        return arrayGoodsId.length;
    }


    @Override
    public String upload(MultipartFile file) throws Exception {
        String fileNameExtension = Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[file.getOriginalFilename().split("\\.").length - 1];
        String fileName = new Date().getTime() + "." + fileNameExtension;
        OSSClient ossClient = (OSSClient) com.nit.lab.utils.OSSUtil.getOSSClient();
//        fileName = "yjzx_rw/" + fileName;
        String bucketName = "nftmarket";
        if (!fileNameExtension.equals("pdf")) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            com.nit.lab.utils.OSSUtil.uploadByInputStream(ossClient, file.getInputStream(), bucketName, fileName, objectMetadata);
        } else {
            com.nit.lab.utils.OSSUtil.uploadByInputStream(ossClient, file.getInputStream(), bucketName, fileName);
        }
        System.out.println("https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + fileName);
        return "https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + fileName;
    }

    @Override
    public List<GoodsEntity> getByUser(String owner) throws Exception{
        return goodsMapper.getByUser(owner);
    }

    @Override
    public TableRspDTO list4TableByListId(TableReqDTO tableReqDTO) throws Exception {
        System.out.println(tableReqDTO);
        System.out.println("开始运行");
        System.out.println(tableReqDTO.parseQueryParam("listId"));
        Long count = goodsMapper.count4TableByListId(
                Long.parseLong(tableReqDTO.parseQueryParam("listId")));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                goodsMapper.list4TableByListId(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        Long.parseLong(tableReqDTO.parseQueryParam("listId"))
                ));
        for(int i=0;i<pagingDTO.getData().size();i++){
            GoodsDTO goodsDTO =  (GoodsDTO) pagingDTO.getData().get(i);
            if(goodsDTO.getCreator2()==null)
            {
                goodsDTO.setCreator2(goodsDTO.getCreator());
            }
            if(goodsDTO.getOwner2()==null){
                goodsDTO.setOwner2(goodsDTO.getOwner());
            }
            pagingDTO.getData().set(i,(Object) goodsDTO);
        }
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addAll(List<GoodsDTO> goodsDTOS) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<GoodsEntity> goodsEntities = new ArrayList<>();
        for (int i = 0; i < goodsDTOS.get(0).getGoodsNum(); i++) {
            GoodsEntity goodsEntity = mapperFactory.getMapperFacade().map(goodsDTOS.get(i), GoodsEntity.class);
            goodsEntity.setStatus(0);
            goodsEntity.setGoodsNumber(i+1);
            goodsEntities.add(goodsEntity);
        }
        System.out.println("1");
        return goodsMapper.addAll(goodsEntities);
    }
}
